import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'
import type { 
  DatabaseConfig, 
  DatabaseInfo, 
  TableInfo, 
  ColumnInfo,
  QueryResult,
  ConnectionStatus
} from '@/types/database'
// @ts-ignore
import { DatabaseService } from '@/services/database'
import { useNotification } from '@/composables/useNotification'

export const useDatabaseStore = defineStore('database', () => {
  // 状态
  const connections = ref<DatabaseConfig[]>([])
  const activeConnectionId = ref<string | null>(null)
  const activeDatabase = ref<string | null>(null)
  const activeTable = ref<string | null>(null)
  
  const connectionStatus = reactive<Record<string, ConnectionStatus>>({})
  const databases = reactive<Record<string, DatabaseInfo[]>>({})
  const tables = reactive<Record<string, TableInfo[]>>({})
  const columns = reactive<Record<string, ColumnInfo[]>>({})
  
  const loading = reactive({
    connections: false,
    databases: false,
    tables: false,
    columns: false,
    query: false
  })
  
  const queryHistory = ref<Array<{
    id: string
    connectionId: string
    database: string
    query: string
    timestamp: Date
    duration: number
    rowCount: number
    error?: string
  }>>([])
  
  const { notify, notifyError, notifySuccess } = useNotification()
  
  // 计算属性
  const activeConnection = computed(() => 
    connections.value.find(c => c.id === activeConnectionId.value)
  )
  
  const activeDatabases = computed(() => 
    activeConnectionId.value ? databases[activeConnectionId.value] || [] : []
  )
  
  const activeTables = computed(() => {
    const key = `${activeConnectionId.value}:${activeDatabase.value}`
    return tables[key] || []
  })
  
  const activeColumns = computed(() => {
    const key = `${activeConnectionId.value}:${activeDatabase.value}:${activeTable.value}`
    return columns[key] || []
  })
  
  const isConnected = computed(() => {
    if (!activeConnectionId.value) return false
    return connectionStatus[activeConnectionId.value]?.connected || false
  })
  
  // Actions
  async function loadConnections() {
    loading.connections = true
    try {
      connections.value = await DatabaseService.getAllConfigs()
      
      // 加载连接状态
      for (const conn of connections.value) {
        connectionStatus[conn.id] = await DatabaseService.getConnectionStatus(conn.id)
      }
    } catch (error) {
      notifyError('Failed to load connections', error)
    } finally {
      loading.connections = false
    }
  }
  
  async function addConnection(config: Omit<DatabaseConfig, 'id'>) {
    try {
      const newConfig = await DatabaseService.saveConfig(config)
      connections.value.push(newConfig)
      notifySuccess('Connection added successfully')
      return newConfig
    } catch (error) {
      notifyError('Failed to add connection', error)
      throw error
    }
  }
  
  async function updateConnection(config: DatabaseConfig) {
    try {
      const updated = await DatabaseService.updateConfig(config)
      const index = connections.value.findIndex(c => c.id === config.id)
      if (index >= 0) {
        connections.value[index] = updated
      }
      notifySuccess('Connection updated successfully')
      return updated
    } catch (error) {
      notifyError('Failed to update connection', error)
      throw error
    }
  }
  
  async function deleteConnection(id: string) {
    try {
      await DatabaseService.deleteConfig(id)
      connections.value = connections.value.filter(c => c.id !== id)
      
      // 清理相关数据
      delete connectionStatus[id]
      delete databases[id]
      Object.keys(tables).forEach(key => {
        if (key.startsWith(id)) delete tables[key]
      })
      Object.keys(columns).forEach(key => {
        if (key.startsWith(id)) delete columns[key]
      })
      
      if (activeConnectionId.value === id) {
        activeConnectionId.value = null
        activeDatabase.value = null
        activeTable.value = null
      }
      
      notifySuccess('Connection deleted successfully')
    } catch (error) {
      notifyError('Failed to delete connection', error)
      throw error
    }
  }
  
  async function testConnection(config: DatabaseConfig) {
    try {
      await DatabaseService.testConnection(config)
      notifySuccess('Connection successful')
      return true
    } catch (error) {
      notifyError('Connection failed', error)
      return false
    }
  }
  
  async function connectToDatabase(connectionId: string) {
    try {
      activeConnectionId.value = connectionId
      await refreshDatabases()
      notifySuccess('Connected successfully')
    } catch (error) {
      notifyError('Failed to connect', error)
      activeConnectionId.value = null
      throw error
    }
  }
  
  async function refreshDatabases() {
    if (!activeConnectionId.value) return
    
    loading.databases = true
    try {
      databases[activeConnectionId.value] = await DatabaseService.listDatabases(activeConnectionId.value)
    } catch (error) {
      notifyError('Failed to load databases', error)
      throw error
    } finally {
      loading.databases = false
    }
  }
  
  async function selectDatabase(name: string) {
    activeDatabase.value = name
    activeTable.value = null
    await refreshTables()
  }
  
  async function refreshTables() {
    if (!activeConnectionId.value || !activeDatabase.value) return
    
    loading.tables = true
    try {
      const key = `${activeConnectionId.value}:${activeDatabase.value}`
      tables[key] = await DatabaseService.listTables(
        activeConnectionId.value, 
        activeDatabase.value
      )
    } catch (error) {
      notifyError('Failed to load tables', error)
      throw error
    } finally {
      loading.tables = false
    }
  }
  
  async function selectTable(name: string) {
    activeTable.value = name
    await refreshColumns()
  }
  
  async function refreshColumns() {
    if (!activeConnectionId.value || !activeDatabase.value || !activeTable.value) return
    
    loading.columns = true
    try {
      const key = `${activeConnectionId.value}:${activeDatabase.value}:${activeTable.value}`
      columns[key] = await DatabaseService.getTableColumns(
        activeConnectionId.value,
        activeDatabase.value,
        activeTable.value
      )
    } catch (error) {
      notifyError('Failed to load columns', error)
      throw error
    } finally {
      loading.columns = false
    }
  }
  
  async function executeQuery(query: string): Promise<QueryResult> {
    if (!activeConnectionId.value || !activeDatabase.value) {
      throw new Error('No active connection or database selected')
    }
    
    loading.query = true
    const startTime = Date.now()
    
    try {
      const result = await DatabaseService.executeQuery(
        activeConnectionId.value,
        query
      )
      
      // 添加到历史记录
      queryHistory.value.unshift({
        id: Date.now().toString(),
        connectionId: activeConnectionId.value,
        database: activeDatabase.value,
        query,
        timestamp: new Date(),
        duration: Date.now() - startTime,
        rowCount: result.rowCount,
        error: result.error
      })
      
      // 限制历史记录数量
      if (queryHistory.value.length > 100) {
        queryHistory.value = queryHistory.value.slice(0, 100)
      }
      
      if (result.error) {
        notifyError('Query failed', result.error)
      }
      
      return result
    } catch (error) {
      notifyError('Failed to execute query', error)
      throw error
    } finally {
      loading.query = false
    }
  }
  
  // 清理函数
  function clearCache(connectionId?: string) {
    if (connectionId) {
      delete databases[connectionId]
      Object.keys(tables).forEach(key => {
        if (key.startsWith(connectionId)) delete tables[key]
      })
      Object.keys(columns).forEach(key => {
        if (key.startsWith(connectionId)) delete columns[key]
      })
    } else {
      // 清理所有缓存
      Object.keys(databases).forEach(key => delete databases[key])
      Object.keys(tables).forEach(key => delete tables[key])
      Object.keys(columns).forEach(key => delete columns[key])
    }
  }
  
  return {
    // 状态
    connections,
    activeConnectionId,
    activeDatabase,
    activeTable,
    connectionStatus,
    loading,
    queryHistory,
    
    // 计算属性
    activeConnection,
    activeDatabases,
    activeTables,
    activeColumns,
    isConnected,
    
    // Actions
    loadConnections,
    addConnection,
    updateConnection,
    deleteConnection,
    testConnection,
    connectToDatabase,
    refreshDatabases,
    selectDatabase,
    refreshTables,
    selectTable,
    refreshColumns,
    executeQuery,
    clearCache
  }
}) 